package com.woniuxy.auth.controller;/*
@author houguai
@create 2021-03-02 15:22
*/

import com.woniuxy.auth.entity.Roles_admin;
import com.woniuxy.auth.jwt.Audience;
import com.woniuxy.auth.jwt.JwtUtil;
import com.woniuxy.ticketcommon.ResponceResult;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("manager")
@CrossOrigin(exposedHeaders = "*")
public class ManagerController {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private Audience audience;

    @PostMapping("login")
    public ResponceResult<Void> login(String account, String password, HttpServletResponse response){


        UsernamePasswordToken token=new UsernamePasswordToken(account,password);

        Subject subject= SecurityUtils.getSubject();

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            return new ResponceResult<>(404,"账号不存在");
        }catch (IncorrectCredentialsException e){
            return new ResponceResult<>(504,"账号不存在");
        }
        int id=1;
        Roles_admin admin=(Roles_admin)subject.getPrincipal();

        String jwt=JwtUtil.createJWT(admin.getId(),account,audience);

        response.setHeader("Authorization",jwt);

        return ResponceResult.SUCCESS;
    }

    @PostMapping("addorder")
    public ResponceResult<Void> addOrder(@RequestHeader("jwt")String jwt ){

        if (JwtUtil.parseJwt(jwt,audience.getBase64Secret())){
            int id=JwtUtil.getUserId(jwt,audience.getBase64Secret());
            String account=JwtUtil.getAccount(jwt,audience.getBase64Secret());
            return ResponceResult.SUCCESS;
        }

        return new ResponceResult<>(400,"fail");
    }

    @PostMapping("getmenu")
    public ResponceResult<Void> getMenu(@RequestHeader("jwt") String jwt) {
        if (JwtUtil.parseJwt(jwt, audience.getBase64Secret())) {
            int id = JwtUtil.getUserId(jwt, audience.getBase64Secret());
            String account = JwtUtil.getAccount(jwt, audience.getBase64Secret());
            return ResponceResult.SUCCESS;
        }
        return new ResponceResult<>(400,"fail");
    }


}
